import os
from pathlib import Path  # 此库限于python 3.0以上版本
import random
import sqlite3

# 抽象出一些常用功能及公共常量

# 常量 ==============
# 品牌名称->店铺缩写代码的映射
BRAND_TO_STORE_CODE = {'LACOZY':'LA', 'INFITTY':'IN'}
# 服装类型枚举
CLOTHING_TYPE =['sweatshirt', 't-shirt', 'dress', 'jumpsuit', 'jacket', 'shacket', 'cardigan', 'sweater', 'skirt', 'bra', 'jean', 'swimsuit', 'pajama', 'vest', 'tank']
SIZE_GROUP=["women", "women's plus"]

# sqlite数据库文件路径
DB_PATH = 'db/data.db'

# 把字符单词组成的list，随机删减/乱序
# 参数 words,list类型
# 返回值 list
def resizeAndShuffle(words):
	total = len(words)
	delta_max = 2*int(total/3)
	delta_rand = random.randint(0, delta_max)
	random.shuffle(words)
	return words[:delta_rand] if delta_rand>0 else words

# 随机乱序拼接item name文案中关键段
# 参数 prd_type 产品类型，也作为核心词使用 key_words list类型，adorn_words list类型
# 返回值 拼接好的字符串类型
def shuffleItemnameKeyseg(prd_type, key_words, adorn_words):
    # 一级修饰词
    new_key_words = key_words.copy()
    random.shuffle(new_key_words)
    # 把核心词放在一级修饰词中间的随机位置，但不作为开头
    kwcount = len(new_key_words)
    rendi = 1
    if kwcount > 1:
        rendi = random.randint(1, kwcount - 1)
    new_key_words.insert(rendi, prd_type)
    # 次级修饰词
    new_adorn_words = resizeAndShuffle(adorn_words)
    # 首字母大写
    new_key_words = list(map(lambda x:x.title(), new_key_words))
    new_adorn_words = list(map(lambda x:x.title(), new_adorn_words))
    return f"{' '.join(new_key_words)} {' '.join(new_adorn_words)}"

# 对item name中的关键文案洗牌
# 参数 prd_type 产品类型，也作为核心词使用 key_words 一级修饰词list, adorn_words 次级修饰词list; e.g. ['v neck', 'long sleeve', ...], ['lace', 'split hem', ...]
# 返回值 字符串 已拼接好，可直接使用的item name
def shuffleItemNameCopywriting(prd_type, key_words, adorn_words):
    # 校验唯一性，最大尝试200次，若超出，则使用最后1次生成的item name
    max_times = 200
    item_name_key_seg = shuffleItemnameKeyseg(prd_type, key_words, adorn_words)
    # 从数据库中校验是否已占用
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    sql = "SELECT * FROM ITEMCOPYWRITING WHERE title='{}'"
    
    try:
        res = c.execute(sql.format(item_name_key_seg))
        unique = not res # list为空可以直接逻辑运算
        count = 1
        while not unique and count<max_times:
            item_name_key_seg = shuffleItemnameKeyseg(prd_type, key_words, adorn_words)
            sql = sql.format(item_name_key_seg)
            res = list(c.execute(sql))
            unique = True if len(res)==0 else False
            # print(f'[Item Name]res:{unique},sql:{sql}')
            count = count + 1
        # 如果次数小于max_times就结束,则说明此次生成的Item Name Copywriting未被占用,则存入DB
        # print(f'[Item Name]try_times:{count}')
        if count<max_times:
            sql = f"INSERT INTO ITEMCOPYWRITING(title) VALUES('{item_name_key_seg}')"
            c.execute(sql)
    except Exception as e:
        print(f'[SQL]{sql}')

    conn.commit()
    conn.close()
    return item_name_key_seg

# 异化Item Name
# 参数 brand 品牌名称, size_group 平台列举的那些尺码类型，字符串, key_words 核心词list, adorn_words 修饰词list, product_type 产品类型
# 参数举例：'LACOZY', "Women's Plus", ['v neck', 'long sleeve', ...], ['lace', 'split hem', ...], ClothingType.JEAN
# 返回值 itemNameCopywriting 字符串; itemName 字符串
def alienateItemName(brand, size_group, key_words, adorn_words, product_type):
    sizegroup = size_group.title()
    ptype = product_type.title()
    copywriting = shuffleItemNameCopywriting(ptype, key_words, adorn_words)
    return copywriting, f"{brand} {sizegroup} {copywriting}"